package net.pingfang.devicelock.Decoder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.concurrent.EventExecutorGroup;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class HHDDecoder extends ByteToMessageDecoder {
    /*
    *
    *
    * */
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        //String HEXES = "0123456789ABCDEF" 是十六进制字符的索引表，通过字符位置可直接映射到对应的十六进制值
        String HEXES = "0123456789ABCDEF";
        //从Netty的ByteBuf缓冲区读取所有可读字节到req数组
        byte[] req = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(req);
        final StringBuilder hex = new StringBuilder(2 * req.length);

        for (int i = 0; i < req.length; i++) {
            byte b = req[i];
            hex.append(HEXES.charAt((b & 0xF0) >> 4))  //处理高4位
                    .append(HEXES.charAt((b & 0x0F)));  //处理低4位
        }

        list.add(hex.toString());
        log.info("hex:{}", hex);
    }
}
